package com.itheima.service.impl;

import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    //注入 mapper 对象
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptLogService deptLogService;

    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    //开启事务注解，并指定异常回滚类型,默认只开启了 RuntimeException 的回滚, Exception.class 是指所有异常都回滚
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(int id) {
        //这里需要通过 @Transactional 注解开启事务管理器，保证数据的一致性，只有部门和员工都删除成功才提交事务，否则回滚事务
        try {
            //级联删除部门
            deptMapper.delete(id);

//            int cont = 1 / 0;//模拟异常，测试事务回滚 这个属于RuntimeException 异常

            //级联删除员工
            empMapper.deleteByDeptId(id);
        } finally {
            //把日志记录到数据库
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("删除部门" + id);

            deptLogService.insert(deptLog);
        }


    }

    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.add(dept);
    }

    @Override
    public Dept query(int id) {
        return deptMapper.query(id);
    }

    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
